package com.ac.api.user.service.impl;

import cn.hutool.http.HttpUtil;
import com.ac.api.user.entity.AcUserInfo;
import com.ac.api.userinfo.entity.AcUserinfo;
import com.ac.api.userinfo.service.AcUserinfoService;
import com.ac.utils.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.context.Context;
import com.base.context.ContextHolder;
import com.base.helper.Result;
import com.base.helper.StringUtils;
import com.ac.api.group.entity.AcGroup;
import com.ac.api.group.service.AcActionPageService;
import com.ac.api.group.service.AcGroupService;
import com.ac.api.user.entity.MbMember;
import com.ac.api.user.service.AcLoginlogService;
import com.ac.api.user.service.MbMemberService;
import com.ac.api.user.dao.AcUserMapper;
import com.ac.api.user.entity.AcUser;
import com.ac.api.user.service.AcUserService;
import com.ac.api.user.vo.*;
import com.ac.utils.PasswordUtil;
import com.ac.utils.WxLoginUtil;
import com.ac.utils.oConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mzl
 * @since 2020-07-09
 */
@Service
@Slf4j
public class AcUserServiceImpl extends ServiceImpl<AcUserMapper, AcUser> implements AcUserService {
    @Autowired
    private AcUserMapper acUserMapper;
    @Autowired
    private AcUserinfoService acUserinfoService;
    @Autowired
    private MbMemberService mbMemberService;
    @Autowired
    private AcGroupService acGroupService;
    @Autowired
    private AcActionPageService acActionPageService;
    @Autowired
    private AcLoginlogService acLoginlogService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    WxService wxService;
    private static final String appid = "wxc1c99e27fac3b752";
    private static final String secret = "b65ebe9f2ad928301d162f0c6093faea";

    @Override
    public Integer getUserId() {
        Context context = ContextHolder.currentContext();
        Integer userId=context.currentUser().getId();
       //如果无法获取，则默认一个用户，测试专用，正式环境必须屏蔽
        if (context.currentToken().equals("fbc545a91cc94fe89296828a25a7e08e@9085553879028596738")){
            userId=96;
        }
        return userId;
    }
    @Override
    public Result<LoginSuccessVo> phoneLogin(String phone, String password) {
        AcUser user = this.findByUserphone(phone);
        if(user==null){
            return new Result<>(false,"用户不存在","");
        }
        if(user!=null && user.getUsertype()!=2){
            return new Result<>(false,"用户不存在","");
        }
        String passwordEncode = PasswordUtil.encrypt(password, "peakfit", user.getSalt());
        if(!passwordEncode.equals(user.getPassword())){
            return new Result<>(false,"密码错误","");
        }
        //      5.登录成功设置令牌
//        Context context = ContextHolder.currentContext();
//        return new Result<>(true,new LoginSuccessVo(acUservo, context.currentToken()));
        acLoginlogService.addLog(user.getId(), user.getUsername(), "t", null);
        Context context = ContextHolder.currentContext();
        return new Result<>(true, normalizeContext(context, user));

    }
//    @Override
//    public Result<LoginSuccessVo> phoneLogin(String username, String password) {
//        AcUserVo acUservo=acUserMapper.getMemberByAccount(username);
//        if(acUservo==null){
//            return new Result<>(false,"用户不存在","");
//        }
//        if(acUservo!=null && acUservo.getUsertype()!=2){
//            return new Result<>(false,"用户不存在","");
//        }
//        String passwordEncode = PasswordUtil.encrypt(password, "pixelai", acUservo.getSalt());
//        if(!passwordEncode.equals(acUservo.getPassword())){
//            return new Result<>(false,"密码错误","");
//        }
//        //      5.登录成功设置令牌
////        Context context = ContextHolder.currentContext();
////        return new Result<>(true,new LoginSuccessVo(acUservo, context.currentToken()));
//        acLoginlogService.addLog(acUservo.getId(), acUservo.getUsername(), "t", null);
//        Context context = ContextHolder.currentContext();
//        return new Result<>(true, normalizeContext(context, acUservo));
//
//    }

    private LoginSuccessVo normalizeContext(Context context, AcUser user) {
        AcGroup acGroup = acGroupService.getById(user.getAcgroup());
        AcUserVo vo      = new AcUserVo(user, acGroup.getGrouptypeid() + "", acGroup.getAcgroup());

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", vo.getId());
        claims.put("username", vo.getUsername());
        claims.put("userpictrue", vo.getPicture());
        claims.put("grouptype", vo.getGrouptype());
        claims.put("usergroup", vo.getUsergroup());
        String token = JWTUtil.genToken(claims);
        user.setPassword(null);
        return new LoginSuccessVo(user,"",token);
    }
    @Override
    public Result<LoginSuccessVo> wxLogin(String code, String encryptedData, String iv) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        String res = HttpUtil.get(replaceUrl);
        AcUserInfo acUserInfo;
        try {
            String wxRes = wxService.wxDecrypt(encryptedData, res,iv);
            log.info("微信解密后的数据："+wxRes);
            acUserInfo = JSON.parseObject(wxRes,AcUserInfo.class);
        }
        catch (Exception e){
            return new Result<>(false,"数据解析失败，后端解密有问题,喊我",e.getMessage());
        }
        //1.获取openid
     String openId =WxLoginUtil.getOpenid(code);
        System.out.println("openId:"+openId);
        System.out.println("openId:"+acUserInfo);
      if(com.aliyun.core.utils.StringUtils.isBlank(openId)){
          return new Result(false, new AcUserVo());
      }
        //测试数据
      //String openId="16606688581";
       //String phone="16606688581";
        //4.根据openid查询数据库  如果有的话就修改手机号， 没有就新增
        AcUser  user=this.findByThirdId(openId);
        //查无此人时新增
        if (user==null) {
            user=new AcUser();
            String salt = oConvertUtils.randomGen(8);
            String passwordEncode = PasswordUtil.encrypt("123456", "peakfit", salt);
            user.setUsername("微信用户"+acUserInfo.getNickName());
            user.setSalt(salt);
            user.setPassword(passwordEncode);
            user.setEnable("1");
            user.setAcgroup(1);
            user.setUsertype(2);
            user.setState("t");
            user.setCreatetime(new Date());
            user.setPwdupdatetime(new Date());
            user.setThirdId(openId);
            user.setThirdType("微信用户");
            user.setIsshow("1");
            user.setPicture(acUserInfo.getAvatarUrl());
            user.setPhone("微信用户");
            this.save(user);
            AcUserinfo acUserinfo=new AcUserinfo();
            acUserinfo.setUserid(user.getId());
            acUserinfo.setIsPrivate("0");
            acUserinfo.setIsHide("0");
            acUserinfo.setUpdataTime(LocalDateTime.now());
            acUserinfo.setUserclock(0);
            acUserinfo.setActivitys(0);
            acUserinfoService.save(acUserinfo);
            user=this.findByThirdId(openId);
            MbMember mbMember=new MbMember();
            mbMember.setUserid(user.getId());
            mbMember.setPhone(acUserInfo.getNickName());
            mbMember.setRegisterTime(new Date());
            mbMember.setLoginTime(new Date());
            mbMember.setNickName("微信用户" + acUserInfo.getNickName());
            mbMemberService.save(mbMember);
        }else{
            if(user.getEnable().equals("0") || user.getState().equals("f")){
                return new Result<>(false,null,"用户已被禁用");
            }
        }
        Context context = ContextHolder.currentContext();
        return new Result<>(true,normalizeContext(context, user));
    }

    @Override
    public IPage<AcUserVo> findByPage(Page page, AcUserVo example) {
        IPage<AcUserVo> resultPage = acUserMapper.findByExample(example,page);
        return resultPage;
    }

    @Override
    public IPage<AcUserVo> findByExample(Integer currentPage, Integer pageSize, AcUserVo example){
        Page<AcUserVo> page = new Page<>(currentPage, pageSize); // currentPage 和 pageSize 根据需要设置
        return baseMapper.findByExample(example,page);
    }

    @Override
    public IPage<AcUserVo> findByGroupid(Integer currentPage, Integer pageSize, Integer groupid) {
        Page<AcUserVo> page = new Page<>(currentPage, pageSize); // currentPage 和 pageSize 根据需要设置
        return baseMapper.findByGroupid(groupid,page);
    }

    private QueryWrapper<AcUserVo> buildWrapper(AcUserVo example) {
        QueryWrapper<AcUserVo> wrapper = new QueryWrapper<>();
        String third_id=example.getThird_id();
        String phone = example.getPhone();
        Integer acgroup = example.getAcgroup();
        Integer usertype = example.getUsertype();
        String username = example.getUsername();
        String enable = example.getEnable();
        wrapper.lambda()
                .like(StringUtils.isNotEmpty(third_id), AcUserVo::getThird_id, third_id)
                .eq(StringUtils.isNotEmpty(phone), AcUserVo::getPhone, phone)
                .eq(null != acgroup, AcUserVo::getAcgroup, acgroup)
                .eq(null != usertype, AcUserVo::getUsertype, usertype)
                .like(StringUtils.isNotEmpty(username), AcUserVo::getUsername, username)
                .eq(StringUtils.isNotEmpty(enable), AcUserVo::getEnable, enable)
                .orderByDesc(AcUserVo::getId);

        // 搜索订单姓名
        String realname = example.getRealname();
        if (StringUtils.isNotEmpty(realname)) {
            wrapper.and(w -> w.like("realname", realname));
        }

        return wrapper;
    }

    @Override
    public AcUser findByUsername(String username) {
        return this.baseMapper.findByUsername(username);
    }
    @Override
    public AcUser findByThirdId(String thirdId) {
        return this.baseMapper.findByThirdId(thirdId);
    }
    @Override
    public AcUser findByUserphone(String phone) {
        return this.baseMapper.findByUserphone(phone);
    }
    @Override
    public AcUser setEnable(Integer id, String enable) {
        AcUser acUser = this.getById(id);
        if (null == acUser || "0".equals(acUser.getState())) {
            throw new RuntimeException("没有找到id对应对象");
        }
        if (enable.equals(acUser.getEnable())) {
            throw new RuntimeException("该订单已经处于该状态");
        }
        acUser.setEnable(enable);
        this.updateById(acUser);
        return acUser;
    }

    @Override
    public AcUser registerExamineeUser(RegisterExamineeVo examinee) {
        AcUser acUser = new AcUser();
        acUser.setUsername(examinee.getUsername());
        acUser.setRealname(examinee.getRealname());
        acUser.setPassword(examinee.getIdentitynum().substring(examinee.getIdentitynum().length() - 6));
        acUser.setAcgroup(examinee.getAcgroup());
        acUser.setUsertype(examinee.getUsertype());
        acUser.setEnable("1");
        acUser.setCreatetime(new Date());
        acUser.setPwdupdatetime(new Date());
        acUser.setState("1");
        if (this.save(acUser)) {
            return this.findByUsername(examinee.getUsername());
        } else {
            return null;
        }
    }

    @Override
    public AcUser registerStudentUser(RegisterStudentVo student) {
        AcUser acUser = new AcUser();
        acUser.setUsername(student.getUsername());
        acUser.setRealname(student.getName());
        acUser.setPassword(student.getExamineenum().substring(student.getExamineenum().length() - 6));
        acUser.setAcgroup(student.getAcgroup());
        acUser.setUsertype(student.getUsertype());
        acUser.setEnable("1");
        acUser.setCreatetime(new Date());
        acUser.setPwdupdatetime(new Date());
        acUser.setState("1");
        if (this.save(acUser)) {
            return this.findByUsername(student.getUsername());
        } else {
            return null;
        }
    }

    @Override
    public AcUser updateUserRealname(Integer id, String realname) {
        AcUser acUser = this.getById(id);
        if (null != acUser && "1".equals(acUser.getState())) {
            acUser.setRealname(realname);
            this.updateById(acUser);
            return acUser;
        }
        return null;
    }

    @Override
    public AcUser setPwd(EnSetPwdVo setPwd) {
        AcUser acUser = this.baseMapper.findByResettoken(setPwd.getToken());
        if (null == acUser || "0".equals(acUser.getState())) {
            throw new RuntimeException("没有找到对应考生");
        }
        acUser.setPassword(setPwd.getPwd());
        super.updateById(acUser);
        return acUser;
    }

    @Override
    public List<AcUser> deleteByUserIds(List<Integer> userIds) {
        QueryWrapper<AcUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(AcUser::getId, userIds);
        List<AcUser> list = super.list(wrapper);
        this.removeByIds(userIds);
        return list;
    }

    @Override
    public List<AcUser> selectByAcGroupAndDepartmentId(Integer acGroup, Integer departmentId) {
        return this.baseMapper.selectByAcGroupAndDepartmentId(acGroup,departmentId);
    }

}
